package com.cj.job;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.connection.MessageListener;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import com.cj.util.RedisObject;
import cn.hutool.core.util.ReUtil;

@Component
public class Sub2 implements CommandLineRunner{
	
	@Autowired
	RedisTemplate<String, String> redisTemplate;
	
	@Autowired
	RedisObject redisObject;
	
	public void PSubscribe(String channnel) {
		System.out.println("开始订阅");
		RedisConnection redisConnection = redisTemplate.getConnectionFactory().getConnection();
		redisConnection.pSubscribe(new MessageListener() {
			
			@Override
			public void onMessage(Message message, byte[] pattern) {
				String newId = new String(message.getBody());
				String channel = new String (message.getChannel());
				String regex = "^__keyevent@(\\d+)__:expired$";
				boolean flag = ReUtil.contains(regex, channel);//这里要用正则来进行匹配
				if(flag!= false) {
					String content = ReUtil.get(regex, channel, 1);
					int db = Integer.parseInt(content);//取出DB不同的DB 需要进行select
					if(ReUtil.contains("news(\\d+)", newId)!= false) {
						String id = ReUtil.get("news(\\d+)", newId, 1);
						//这个是我们自己封装的Redis Object
						redisObject.multiExec(redisTemplate, redisConnection, db, Long.valueOf(id));
					}
				}
				System.out.println("clear news cache,newsID="+newId+" done~~~");
				
			}
		}, channnel.getBytes());
		
	}
	
	@Override
	public void run(String... args) throws Exception {
		String channel = "__keyevent@*__:expired";
		PSubscribe(channel);
	}
	

}
